package com.ccteam.fluidmusic.ui.music

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ccteam.fluidmusic.utils.Event
import com.ccteam.fluidmusic.utils.cancelIfActive
import com.ccteam.fluidmusic.view.bean.ErrorMessage
import com.ccteam.fluidmusic.view.bean.LoadMessage
import com.ccteam.model.Resource
import com.ccteam.shared.domain.music.MusicInfoDataUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/4/30
 *
 * 获取歌曲详情信息ViewModel
 */
@HiltViewModel
class MusicInfoViewModel @Inject constructor(
    private val musicInfoDataUseCase: MusicInfoDataUseCase
): ViewModel() {

    private val _loadMessage = MutableLiveData<Event<LoadMessage>>()
    val loadMessage: LiveData<Event<LoadMessage>> get() = _loadMessage

    var currentMediaId: String = ""
    private set

    private var musicLoadJob: Job? = null

    fun prepareMusic(mediaId: String){
        musicLoadJob.cancelIfActive()
        _loadMessage.value = Event(LoadMessage.Loading)
        musicLoadJob = viewModelScope.launch {
            val result = musicInfoDataUseCase(mediaId)
            if(result is Resource.Success){
                currentMediaId = mediaId
                _loadMessage.value = Event(LoadMessage.Success)
            } else {
                _loadMessage.value = Event(LoadMessage.Error(ErrorMessage(result.message,result.errorCode)))
            }
        }
    }

    override fun onCleared() {
        super.onCleared()

        musicLoadJob?.cancelIfActive()
    }
}